package com.apes.autoparts.searcher.model;

import com.alibaba.fastjson.JSONArray;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.util.Tools;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Setter
public class EpcCategoryTree {
    String id; // 当前编号

    String name; // 当前名称

    String epcId; // epc编码

    String epcVersion; // epc版本

    int level; // 当前等级

    String parentId; // 上级目录

    boolean lastStage; // 末级标记

    String order; //序号

    String urls; // 图片地址

    String remake1; // 备注1

    String remake2; // 备注2

    public void setChildren(List<EpcCategoryTree> children) {
        this.children = children == null ? new ArrayList() : children;
    }

    List<EpcCategoryTree> children = new ArrayList();



    static public List<EpcCategoryTree> convertTree(JSONArray param, String convertMap) {

        //通用转化map
        List<EpcCategoryTree> paramList = param.stream().map(item -> {
            Map tempMap = SpringManager.getBean(DomainService.class).invoke(convertMap, item);
            return Tools.map(tempMap, EpcCategoryTree.class);
        }).collect(Collectors.toCollection(ArrayList::new));

        // 根据等级分层(多层级， 按照上下级以及 level区分)
        Map<Integer, List<EpcCategoryTree>> levelGroup = paramList.stream().
                collect(Collectors.groupingBy(json -> json.getLevel()));

        // 按层级从大到小排序,拼接树形结构

        return convertTree(levelGroup);
    }


    static private List<EpcCategoryTree> convertTree( Map<Integer, List<EpcCategoryTree>> levelGroup) {
        List<EpcCategoryTree> cacheList = new ArrayList();
        levelGroup.keySet().stream().sorted(Comparator.reverseOrder()).forEach(level -> {
            if (level == 1) {
                cacheList.addAll(levelGroup.get(level));
            } else {
                List<EpcCategoryTree> tempList = levelGroup.get(level - 1);
                List<EpcCategoryTree> currentList = levelGroup.get(level);
                currentList.stream().forEach(item -> {
                    EpcCategoryTree parentNode = tempList.stream().filter(parent -> {
                        return parent.getId().equals(item.getParentId());

                    }).findFirst().orElse(null);
                    if (parentNode != null) {
                        parentNode.getChildren().add(item);
                    }
                });
            }
        });
        return cacheList;
    }
}
